package com.nantian.security.controller;

import com.cuit.springboot.gdao.user.RoleAbilityMapper;
import com.nantian.logic.utils.UniversalResult;
import com.nantian.model.security.User;
import com.nantian.security.JwtTokenUtil;
import com.nantian.security.JwtUser;
import com.nantian.security.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserRestController {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleAbilityMapper roleAbilityMapper;
    /**
     * 从token中获取userId
     * */
    @RequestMapping(value = "user", method = RequestMethod.GET)
    public UniversalResult getAuthenticatedUser(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader).substring(7);
        String userId = jwtTokenUtil.getUserIdFromToken(token);
        return new UniversalResult<>(UniversalResult.SUCCESS,"",userId);
    }

    /**
     * 根据Token获取用户信息
     * @param request
     * @return
     */
    @RequestMapping(value = "userInfo", method = RequestMethod.GET)
    public UniversalResult getUserInfo(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();
        String token = request.getHeader(tokenHeader).substring(7);
        String userId = jwtTokenUtil.getUserIdFromToken(token);
        User user = userRepository.findByUserid(userId);
        user.setPassword("");
        user.setAuthorities(new ArrayList<>());
        map.put("userInfo",user);
        map.put("ability",roleAbilityMapper.attachAbility(user.getRoletype()));
        return new UniversalResult<>(UniversalResult.SUCCESS,"获取用户信息成功",map);
    }

}
